import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from '@/route/routes'
import store from '@/store'


Vue.use(VueRouter)


// 重写push 方法 解决重复跳转同一个路由 处理返回出错误的Promise对象
const oldPush = VueRouter.prototype.push
VueRouter.prototype.push = function (location, onComplete = () => { }, onAbort = () => { }) {
    oldPush.call(this, location, onComplete, onAbort)
}


const router = new VueRouter({
    mode: 'history',
    routes: routes,
    scrollBehavior() {
        return { x: 0, y: 0 }
    }
})

// console.log(router);


// console.log(oldPush);
// router.prototype.push = function (location, resolve = () => { }, reject = () => { }) {
//     oldPush.call(this, location, resolve, reject)
// }

const whitePath = ['login', 'register', 'home', 'search', 'detail', 'addsuccess']

router.beforeEach(async (to, from, next) => {
    let token = store.state.user.token

    let userInfo = store.state.user.userInfo
    if (token) {
        if (to.name === 'login') {
            next('/home')
        } else {
            if (userInfo.id) {
                next();
            } else {
                try {
                    await store.dispatch('user/getUserInfo')
                    next();
                } catch (e) {
                    alert(e.message + '登录已过期')
                    store.commit('user/resetUserInfo')
                    next('/login')
                }
            }
        }
    } else {
        if (whitePath.includes(to.name)) {
            next();
        } else {
            next('/login')
        }
    }
})


export default router
